#!/usr/bin/env python3
"""
通途API调试脚本
用于诊断API连接问题
"""

import requests
import hashlib
import time
import json

def debug_tongtool_api(app_key, app_secret):
    """调试通途API连接"""
    
    print("=== 通途API连接调试 ===")
    print(f"App Key: {app_key[:8]}...")
    print(f"App Secret: {'*' * len(app_secret)}")
    print()
    
    # 步骤1: 测试获取app_token
    print("步骤1: 获取app_token")
    auth_url = "https://open.tongtool.com/open-platform-service"
    
    try:
        token_response = requests.get(
            f"{auth_url}/devApp/appToken",
            params={
                'accessKey': app_key,
                'secretAccessKey': app_secret
            },
            timeout=30
        )
        
        print(f"请求URL: {token_response.url}")
        print(f"响应状态: {token_response.status_code}")
        print(f"响应头: {dict(token_response.headers)}")
        
        if token_response.status_code == 200:
            token_result = token_response.json()
            print(f"响应内容: {json.dumps(token_result, indent=2, ensure_ascii=False)}")
            
            if token_result.get('success'):
                app_token = token_result['datas']
                print(f"✅ app_token获取成功: {app_token}")
                
                # 步骤2: 测试获取商户信息
                print("\n步骤2: 获取商户信息")
                timestamp = int(time.time())
                sign = hashlib.md5(
                    f"app_token{app_token}timestamp{timestamp}{app_secret}".encode()
                ).hexdigest()
                
                print(f"timestamp: {timestamp}")
                print(f"sign字符串: app_token{app_token}timestamp{timestamp}{app_secret}")
                print(f"sign: {sign}")
                
                merchant_response = requests.get(
                    f"{auth_url}/partnerOpenInfo/getAppBuyerList",
                    params={
                        'app_token': app_token,
                        'timestamp': timestamp,
                        'sign': sign
                    },
                    timeout=30
                )
                
                print(f"商户信息请求URL: {merchant_response.url}")
                print(f"商户信息响应状态: {merchant_response.status_code}")
                
                if merchant_response.status_code == 200:
                    merchant_result = merchant_response.json()
                    print(f"商户信息响应: {json.dumps(merchant_result, indent=2, ensure_ascii=False)}")
                    
                    if merchant_result.get('success') and merchant_result.get('datas'):
                        merchants = merchant_result['datas']
                        if merchants:
                            merchant_id = merchants[0]['partnerOpenId']
                            print(f"✅ 商户ID获取成功: {merchant_id}")
                            return True, merchant_id
                        else:
                            print("❌ 未找到商户信息")
                            return False, "未找到商户信息"
                    else:
                        print(f"❌ 获取商户信息失败: {merchant_result.get('message', '未知错误')}")
                        return False, merchant_result.get('message', '未知错误')
                else:
                    print(f"❌ 商户信息请求失败: {merchant_response.status_code}")
                    print(f"响应内容: {merchant_response.text}")
                    return False, f"HTTP {merchant_response.status_code}"
                    
            else:
                print(f"❌ token获取失败: {token_result.get('message', '未知错误')}")
                return False, token_result.get('message', '未知错误')
        else:
            print(f"❌ token请求失败: {token_response.status_code}")
            print(f"响应内容: {token_response.text}")
            return False, f"HTTP {token_response.status_code}"
            
    except requests.exceptions.RequestException as e:
        print(f"❌ 网络请求失败: {str(e)}")
        return False, f"网络错误: {str(e)}"
    except Exception as e:
        print(f"❌ 未知错误: {str(e)}")
        return False, f"未知错误: {str(e)}"


def test_api_direct():
    """直接测试API（需要手动输入凭证）"""
    print("请输入你的通途API凭证:")
    app_key = input("App Key: ").strip()
    app_secret = input("App Secret: ").strip()
    
    if not app_key or not app_secret:
        print("❌ App Key和App Secret不能为空")
        return
    
    success, result = debug_tongtool_api(app_key, app_secret)
    
    if success:
        print(f"\n🎉 API测试成功！商户ID: {result}")
    else:
        print(f"\n💥 API测试失败: {result}")


def test_network_connectivity():
    """测试网络连接性"""
    print("=== 网络连接性测试 ===")
    
    test_urls = [
        "https://open.tongtool.com",
        "https://open.tongtool.com/open-platform-service",
        "https://open.tongtool.com/api-service"
    ]
    
    for url in test_urls:
        try:
            response = requests.get(url, timeout=10)
            print(f"✅ {url} - 状态: {response.status_code}")
        except Exception as e:
            print(f"❌ {url} - 错误: {str(e)}")


if __name__ == "__main__":
    print("通途API调试工具")
    print("1. 测试网络连接")
    print("2. 测试API认证")
    
    choice = input("请选择 (1/2): ").strip()
    
    if choice == "1":
        test_network_connectivity()
    elif choice == "2":
        test_api_direct()
    else:
        print("无效选择")
